﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Kaskelot.SP.Model.Client.Forms;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;

namespace Kaskelot.SP.Services.Client.Mapping
{
	public static class ClientValkretsExtensions
	{
		public static ClientValkrets ToClientContract(this Valkrets contract)
		{
			ClientValkrets b = new ClientValkrets();

			CopyFromContract(contract, b, false);

			return b;
		}

		public static ClientValkrets ToMinimalClientContract(this Valkrets contract)
		{
			ClientValkrets b = new ClientValkrets();

			CopyFromContract(contract, b, true);

			return b;
		}

		public static Valkrets ToContract(this ClientValkrets b)
		{
			Valkrets Contract = new Valkrets();

			CopyToContract(b, Contract);

			return Contract;
		}

		public static Valkrets UpdateContract(this Valkrets valkrets, ValkretsForm form)
		{
			if (valkrets.Id == Guid.Empty)
			{
				valkrets.Id = Guid.NewGuid();
			}
			valkrets.Namn = form.Namn;
			valkrets.ValkretsNr = form.ValkretsNr;

			return valkrets;
		}

		private static void CopyFromContract(Valkrets from, ClientValkrets to, bool minimal)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.Namn = from.Namn;
			
			to.Andrad = from.Andrad != null ? from.Andrad.ToString() : null;
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad != null ? from.Skapad.ToString() : null;
			to.SkapadAv = from.SkapadAv;

			to.ValkretsNr = from.ValkretsNr;

			if (minimal) return;
			to.Val = from.Val.ToMinimalClientContract();

			if (from.Forsamlingar != null)
			{
				to.Forsamlingar = new List<ClientForsamling>();
				foreach (Forsamling f in from.Forsamlingar)
				{
					to.Forsamlingar.Add(f.ToMinimalClientContract());
				}
			}
		}

		private static void CopyToContract(ClientValkrets from, Valkrets to)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.Namn = from.Namn;

			if (!String.IsNullOrEmpty(from.Andrad))
				to.Andrad = DateTime.Parse(from.Andrad);
			else
				to.Andrad = null;

			to.AndradAv = from.AndradAv;

			if (from.Skapad != null)
				to.Skapad = DateTime.Parse(from.Skapad);

			to.ValkretsNr = from.ValkretsNr;
		}
	}
}
